"use client";

import { authApi } from '@/constants';
import { post, get, del, commonHooks } from '@/util/api';

// 用户类型定义
export interface User {
  id: string;
  username: string;
  role?: number;
  nickname?: string;
  avatar?: string;
  [key: string]: any;
}

// 登录表单数据类型
export interface LoginFormData {
  username: string;
  password: string;
  remember?: boolean;
}

// 登录响应类型
export interface LoginResponse {
  code?: number;
  message?: string;
  data?: {
    access_token: string;
    admin: User;
  };
  access_token?: string;
  admin?: User;
}

/**
 * 认证服务类
 * 封装所有授权登录相关的 API 调用和本地存储管理
 */
class AuthService {
  /**
   * 用户登录
   * @param credentials 登录凭证
   * @returns Promise<LoginResponse>
   */
  async login(credentials: LoginFormData): Promise<LoginResponse> {
    try {
      // 调用管理员专属登录接口
      const response = await post(authApi.LOGIN, {
        username: credentials.username,
        password: credentials.password,
      });
      
      // 检查响应数据并存储认证信息
      if (response.code === 200 || !response.code) {
        const { access_token, admin } = (response.data || response) as LoginResponse;
        
        if (access_token && admin) {
          // 存储令牌和用户信息到本地存储
          this.setAuthData(access_token, admin, credentials.remember);
        }
      }
      
      return response as LoginResponse;
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  }

  /**
   * 用户登出
   */
  async logout(): Promise<void> {
    try {
      // 尝试调用登出API（可选，如果服务器需要），添加认证token
      //await post(authApi.LOGOUT, {}, {
      //  beforeRequest: commonHooks.addAuthToken
      //});
    } catch (error) {
      console.error('登出API调用失败，但仍会清除本地认证数据:', error);
    } finally {
      // 确保清除本地存储的认证数据
      this.clearAuthData();
    }
  }

  /**
   * 获取当前登录用户信息
   * @returns Promise<User | null>
   */
  async getCurrentUser(){
    try {
      // 调用获取当前用户信息的API，添加认证token
      const response = await get(authApi.CURRENT_USER);
      console.log('获取用户信息 response:', response);
      return response || null;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return this.getUserFromStorage();
    }
  }

  /**
   * 刷新认证令牌
   * @returns Promise<string | null>
   */
  async refreshToken(): Promise<string | null> {
    try {
      // 刷新令牌也需要携带认证token
      const response = await post(authApi.REFRESH_TOKEN, {}, {
        beforeRequest: commonHooks.addAuthToken
      });
      
      if (response.code === 200 || !response.code) {
        const { access_token } = (response.data || response) as LoginResponse;
        
        if (access_token) {
          // 更新令牌但保留用户信息
          const user = this.getUserFromStorage();
          if (user) {
            this.setAuthData(access_token, user, true);
          }
          return access_token;
        }
      }
      
      return null;
    } catch (error) {
      console.error('刷新令牌失败:', error);
      return null;
    }
  }

  /**
   * 检查用户是否已认证
   * @returns boolean
   */
  isAuthenticated(): boolean {
    const token = this.getTokenFromStorage();
    // console.log('isAuthenticated:', token);
    return !!token;
  }

  /**
   * 从本地存储获取令牌
   * @returns string | null
   */
  private getTokenFromStorage(): string | null {
    const token = localStorage.getItem('admin_token'); 
    // console.log('getTokenFromStorage:', token);
    return token;
  }

  /**
   * 从本地存储获取用户信息
   * @returns User | null
   */
  private getUserFromStorage(): User | null {
    try {
      const userStr = localStorage.getItem('admin_info');
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      console.error('解析用户信息失败:', error);
      return null;
    }
  }

  /**
   * 设置认证数据到本地存储
   * @param token 访问令牌
   * @param user 用户信息
   * @param remember 是否记住登录状态
   */
  setAuthData(token: string, user: User, remember: boolean = false): void {
    if (remember) {
      // 如果记住登录，则使用localStorage
      localStorage.setItem('admin_token', token);
      localStorage.setItem('admin_info', JSON.stringify(user));
    } else {
      // 否则使用sessionStorage
      sessionStorage.setItem('admin_token', token);
      sessionStorage.setItem('admin_info', JSON.stringify(user));
    }
  }

  /**
   * 清除本地存储中的认证数据
   */
  private clearAuthData(): void {
    // 清除所有可能的认证数据键
    localStorage.removeItem('admin_token');
    localStorage.removeItem('admin_info');
    sessionStorage.removeItem('admin_token');
    sessionStorage.removeItem('admin_info');
  }
}

// 导出单例实例
export const authService = new AuthService();

// 默认导出
export default authService;